package cn.com.czpb.client.module.personal;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.bumptech.glide.Glide;
import com.tbruyelle.rxpermissions.RxPermissions;
import com.uuzuche.lib_zxing.activity.CaptureActivity;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import cn.com.czpb.client.R;
import cn.com.czpb.client.api.InterfaceJsonfile;
import cn.com.czpb.client.app.BaseFragment;
import cn.com.czpb.client.model.event.DayNightEvent;
import cn.com.czpb.client.model.usercenter.EmptyEntity;
import cn.com.czpb.client.model.usercenter.IsSignEntity;
import cn.com.czpb.client.model.usercenter.LevelEntity;
import cn.com.czpb.client.model.usercenter.ThirdLoginBean;
import cn.com.czpb.client.model.usercenter.UserEntity;
import cn.com.czpb.client.module.actives.activity.HuodongActivity;
import cn.com.czpb.client.module.baoliao.BaoliaoActivity;
import cn.com.czpb.client.module.dialog.ShareDialog;
import cn.com.czpb.client.module.news.activity.CircleActivity;
import cn.com.czpb.client.module.personal.acticity.CollectionActivity;
import cn.com.czpb.client.module.personal.acticity.HistoryActivity;
import cn.com.czpb.client.module.personal.acticity.LoginActivity;
import cn.com.czpb.client.module.personal.acticity.MessageActivity;
import cn.com.czpb.client.module.personal.acticity.MyCommActivity;
import cn.com.czpb.client.module.personal.acticity.MyShareActivity;
import cn.com.czpb.client.module.personal.acticity.PersonPageActivity;
import cn.com.czpb.client.module.personal.acticity.UserSuggestActivity;
import cn.com.czpb.client.net.Factory;
import cn.com.czpb.client.utils.AAnim;
import cn.com.czpb.client.utils.LogUtils;
import cn.com.czpb.client.utils.PageCtrl;
import cn.com.czpb.client.utils.ParamUtils;
import cn.com.czpb.client.utils.TUtils;
import cn.com.czpb.client.utils.TextUtils;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.PlatformDb;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;
import de.greenrobot.event.EventBus;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by 猪猪侠 on 2017/7/3.
 */

public class WodeFragment extends BaseFragment {
    @BindView(R.id.photo_usercenter_main)
    ImageView photo_usercenter_main;
    @BindView(R.id.name_usercenter_main)
    TextView name_usercenter_main;
    @BindView(R.id.name_1_usercenter_main)
    TextView name_1_usercenter_main;
    @BindView(R.id.dingyue_usercenter_main)
    RelativeLayout dingyue_usercenter_main;
    @BindView(R.id.collection_usercenter_main)
    RelativeLayout collection_usercenter_main;
    @BindView(R.id.qiandao_user_main)
    TextView qiandao_user_main;
    @BindView(R.id.desc_usercenter_main)
    TextView Desc_usercenter_main;
    @BindView(R.id.ll_login)
    LinearLayout ll_login;
    @BindView(R.id.togglebutton_huyan)
    ToggleButton toggleButton_huyan;
    LoginQuitBR br;
    Unbinder unbinder;
    private boolean isDayOrNight;
    public static final String ACTION_USER = "com.hzpd.cms.user";
    public static final String ACTION_QUIT = "com.hzpd.cms.quit";//退出登录;
    public static final String ACTION_QUIT_LOGIN = "com.hzpd.cms.quit.login";
public static final int REQUEST_CODE = 100;
    private static final String[] PERMISSIONS = new String[]{
            Manifest.permission.CAMERA,//照相机权限
//            Manifest.permission.WRITE_EXTERNAL_STORAGE,//写入存储的权限;
//            Manifest.permission.READ_PHONE_STATE,//写入存储的权限;
//            Manifest.permission.ACCESS_COARSE_LOCATION,//地址
    };
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {

                case 888: {
                    Platform plat = (Platform) msg.obj;
                    PlatformDb platDB = plat.getDb();
                    // 通过DB获取各种数据
                    String token = platDB.getToken();
                    String gender = platDB.getUserGender();
                    String usericon = platDB.getUserIcon();
                    String userid = platDB.getUserId();
                    String username = platDB.getUserName();
                    String userplatform = platDB.getPlatformNname();
                    LogUtils.i("token" + token + " gender:" + gender + " usericon:"
                            + usericon + " userid:" + userid + " username:"
                            + username + " userplatform:" + userplatform);
                    ThirdLoginBean tlb = new ThirdLoginBean(userid, gender,
                            username, usericon, userplatform);
                    thirdLogin(tlb);
                }
                break;
                case 889: {
                    TUtils.toast("登陆失败");
                }
                break;
                case 890: {
                    TUtils.toast("登录取消");
                }
                case 100: {
                    Platform plat = (Platform) msg.obj;
//					LogUtils.i("plat--->"+plat.toString());
                }
                break;

                case 333: {


                }
                break;
                case 444: {


                }
                break;
                case 555: {
                    TUtils.toast("验证码错误");

                }
                break;
                case 445: {
                    TUtils.toast("验证码获取成功");


                }
                break;
                case 446: {
                    TUtils.toast("验证码获取失败");


                }
                break;
            }
        }
    };


    @Override
    public int setMyContentView() {
        return R.layout.fragment_usercenter_main;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        br = new LoginQuitBR();
        IntentFilter filter = new IntentFilter();
        filter.addAction(ACTION_QUIT);
        filter.addAction(ACTION_USER);
        filter.addAction(ACTION_QUIT_LOGIN);
        activity.registerReceiver(br, filter);
        isDayOrNight = spu.getIsNight();//判断是否是夜间模式//false 日间
        mImmersionBar.statusBarDarkFont(true).init();
        toggleButton_huyan.setChecked(isDayOrNight);

        if (spu.getUser() != null) {
            setLogin();
//            Glide.with(getActivity()).load(spu.getUser().getAvatar_path()).crossFade().into(photo_usercenter_main);
//            name_usercenter_main.setText(spu.getUser().getNickname());
//            name_usercenter_main.setVisibility(View.VISIBLE);
//            name_1_usercenter_main.setVisibility(View.GONE);
//            Desc_usercenter_main.setVisibility(View.VISIBLE);
//            qiandao_user_main.setVisibility(View.VISIBLE);
        }

    }

    public static WodeFragment newInstance() {
        WodeFragment userCenterFragment = new WodeFragment();
        return userCenterFragment;
        /////////
    }

    @Override
    public void initView() {

    }

    @Override
    public void initData() {

    }

    @OnClick(R.id.qiandao_user_main)
    public void QianDao(View view) {

        QianDao();
    }

    @OnClick(R.id.set_my)
    public void Set(View view) {
        PageCtrl.start2SystemSetActivity(activity);
    }

    @OnClick({
            R.id.rl_baoliao_id,
            R.id.rl_active_id,
            R.id.photo_usercenter_main,
            R.id.login_usercenter_main,
            R.id.collection_usercenter_main,
            R.id.share_usercenter_main,
            R.id.invite_usercenter_main,
            R.id.saoyisao_usercenter_main,
            R.id.history_usercenter_main,
            R.id.dingyue_usercenter_main,
            R.id.message_usercenter_main,
            R.id.fankui_set_activity,
            R.id.togglebutton_huyan,
            R.id.tv_login,
            R.id.ll_baoliao,
            R.id.ll_mbaoliao,
            R.id.rl_circle_id
    })
    public void Click(View view) {
        boolean flag = false;
        Intent mIntent = new Intent();
        switch (view.getId()) {
            case R.id.rl_circle_id:
                flag = true;
                if (spu.getUser() == null) {
                    mIntent.setClass(activity, LoginActivity.class);
                }else{
                    mIntent.setClass(activity, CircleActivity.class);
                }

                break;
            case R.id.ll_baoliao:
                flag = true;
                mIntent.putExtra("type",BaoliaoActivity.TYPE_0);
                mIntent.setClass(activity, BaoliaoActivity.class);
                break;
            case R.id.ll_mbaoliao:
                flag = true;
                mIntent.putExtra("type",BaoliaoActivity.TYPE_1);
                mIntent.setClass(activity, BaoliaoActivity.class);
                break;
            case R.id.rl_baoliao_id:
                flag = true;
                mIntent.setClass(activity, BaoliaoActivity.class);
                break;
            case R.id.rl_active_id:
                flag = true;
                mIntent.setClass(activity, HuodongActivity.class);
                break;

            case R.id.photo_usercenter_main:
            case R.id.login_usercenter_main:
                flag = true;
                if (spu.getUser() == null) {
                    mIntent.setClass(activity, LoginActivity.class);
                } else {
                    mIntent.putExtra("uid", spu.getUser().getUid());
                    mIntent.setClass(activity, PersonPageActivity.class);
                }
                break;
            case R.id.collection_usercenter_main:
                if (spu.getUser() != null) {
                    flag = true;
                    mIntent.setClass(activity, CollectionActivity.class);
                } else {
                    flag = true;
                    mIntent.setClass(activity, LoginActivity.class);
                    TUtils.toast("请先登录");
                }
                break;
            case R.id.tv_login:
                flag = true;
                mIntent.setClass(activity, LoginActivity.class);
                break;
            case R.id.history_usercenter_main:
                if (spu.getUser() != null) {
                    flag = true;
                    mIntent.setClass(activity, HistoryActivity.class);
                } else {
                    flag = true;
                    mIntent.setClass(activity, LoginActivity.class);
                    TUtils.toast("请先登录");
                }
                break;
            case R.id.dingyue_usercenter_main:
                if (spu.getUser() != null) {
                    flag = true;
                    mIntent.setClass(activity, MessageActivity.class);
                } else {
                    flag = true;
                    mIntent.setClass(activity, LoginActivity.class);
                    TUtils.toast("请先登录");
                }
                break;
            case R.id.share_usercenter_main:
                //新需求：邀请码功能
//                flag = true;
//                mIntent.setClass(activity, MyShareActivity.class);
                ShareDialog dialog = new ShareDialog(activity, R.style.Sharedialog, "扫描二维码,下载【广西云】", InterfaceJsonfile.INVITEURL, InterfaceJsonfile.PATH_ROOT_INVITE, 0);
                dialog.show();
                break;
            case R.id.invite_usercenter_main:
//                //新需求：邀请码功能
                flag = true;
                mIntent.setClass(activity, MyShareActivity.class);
//                ShareDialog dialog = new ShareDialog(activity, R.style.Sharedialog, null, InterfaceJsonfile.INVITEURL, null, 0);
//                dialog.show();
                break;

            case R.id.message_usercenter_main:
                if (spu.getUser() != null) {
                    flag = true;
                    mIntent.setClass(activity, MyCommActivity.class);
                } else {
                    flag = true;
                    mIntent.setClass(activity, LoginActivity.class);
                    TUtils.toast("请先登录");
                }
                break;
            case R.id.fankui_set_activity:
                flag = true;
                mIntent.setClass(activity, UserSuggestActivity.class);
                break;
            case R.id.saoyisao_usercenter_main:


                checkPermission();


                break;
            case R.id.togglebutton_huyan:
                if (!isDayOrNight) {//日间
                    toggleButton_huyan.setChecked(true);
                    isDayOrNight = true;
                    setIsNight();
                } else {
                    toggleButton_huyan.setChecked(false);
                    isDayOrNight = false;
                    setIsNight();
                }
                break;
        }
        if (flag) {
            startActivity(mIntent);
            AAnim.ActivityStartAnimation(activity);
        }
    }

    private void checkPermission() {
        RxPermissions.getInstance(activity)
                .request(PERMISSIONS)
                .subscribe(new Action1<Boolean>() {
                    @Override
                    public void call(Boolean granted) {
                        LogUtils.i("granted-->"+granted);
                        if (!granted) {
                            TUtils.toast("缺少照相权限");
                        } else {
                            Intent intent = new Intent(activity, CaptureActivity.class);
                            startActivityForResult(intent, REQUEST_CODE);

                        }
                    }
                });


    }

    //设置日间还是夜间模式
    private void setIsNight() {
        spu.setIsNight(isDayOrNight);
        spu.changeAppBrightness(activity, isDayOrNight);
        DayNightEvent event = new DayNightEvent();
        event.setmFlagSelectNight(isDayOrNight);
        EventBus.getDefault().post(event);
    }

    @Override
    public void onResume() {
        super.onResume();
        if (spu.getUser() != null) {
            isQianDao();
        }

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    public class LoginQuitBR extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(ACTION_USER)) {
                setLogin();
            } else if (action.equals(ACTION_QUIT)) {
                setQuit();
                LogUtils.i("setquit");
            } else if (action.equals(ACTION_QUIT_LOGIN)) {
                setQuit();
                LogUtils.i("setquitlogin");

                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
//                        zy_rfrag_ll_login.callOnClick();
                        LogUtils.i("r_login_layout.callOnClick()");
                    }
                }, 500);
            }
        }
    }

    private void setQuit() {
        ll_login.setVisibility(View.VISIBLE);
        photo_usercenter_main.setImageResource(R.drawable.head);
        name_usercenter_main.setText("");
        collection_usercenter_main.setVisibility(View.VISIBLE);
        dingyue_usercenter_main.setVisibility(View.VISIBLE);
        qiandao_user_main.setVisibility(View.VISIBLE);
        Desc_usercenter_main.setText("");
        Desc_usercenter_main.setVisibility(View.GONE);
        name_1_usercenter_main.setVisibility(View.VISIBLE);
        photo_usercenter_main.setImageResource(R.drawable.head);
    }

    @OnClick({
            R.id.login_qq,
            R.id.login_weibo,
            R.id.login_weixin})
    public void ThirdLogin(View view) {
        TUtils.toast("第三方登录");
        Platform platform = null;

        switch (view.getId()) {

            case R.id.login_qq:
                platform = ShareSDK.getPlatform(QQ.NAME);
                if (platform.isAuthValid()) {
                    platform.removeAccount(true);
                }
                break;
            case R.id.login_weibo:
                platform = ShareSDK.getPlatform(SinaWeibo.NAME);
                if (platform.isAuthValid()) {
                    platform.removeAccount(true);
                }
                break;
            case R.id.login_weixin:
                platform = ShareSDK.getPlatform(Wechat.NAME);
                if (platform.isAuthValid()) {
                    platform.removeAccount(true);
                }
                break;
        }
        platform.setPlatformActionListener(new PlatformActionListener() {
            @Override
            public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
                if (Platform.ACTION_USER_INFOR == i) {
                    Message msg = handler.obtainMessage();
                    msg.what = 888;
                    msg.obj = platform;
                    handler.sendMessage(msg);
                }
            }

            @Override
            public void onError(Platform platform, int i, Throwable throwable) {
                platform.removeAccount(true);
                handler.sendEmptyMessage(889);
            }

            @Override
            public void onCancel(Platform platform, int i) {
                platform.removeAccount(true);
                handler.sendEmptyMessage(890);
            }
        });
        platform.SSOSetting(false);
        platform.showUser(null);// 执行登录，登录后在回调里面获取用户资料
    }

    private void setLogin() {
        ll_login.setVisibility(View.GONE);
        name_usercenter_main.setVisibility(View.VISIBLE);
        collection_usercenter_main.setVisibility(View.VISIBLE);
        dingyue_usercenter_main.setVisibility(View.VISIBLE);
        Glide.with(getActivity()).load(spu.getUser().getAvatar_path()).crossFade().into(photo_usercenter_main);
        name_usercenter_main.setText(TextUtils.getLengthText(spu.getUser().getNickname(), 9));
        qiandao_user_main.setVisibility(View.VISIBLE);
        Desc_usercenter_main.setText(spu.getUser().getDesc());
        Desc_usercenter_main.setVisibility(View.VISIBLE);
        name_1_usercenter_main.setVisibility(View.GONE);
    }

    private void QianDao() {
        Map<String, String> map = new HashMap<>();
        if (spu.getUser() != null) {
            map.put("uid", spu.getUser().getUid());
        }
        Factory.provideHttpService().UserSign(ParamUtils.getRequestParam(map))
                .onBackpressureBuffer()
                .subscribeOn(Schedulers.io())
                .filter(new Func1<EmptyEntity, Boolean>() {
                    @Override
                    public Boolean call(EmptyEntity superEntity) {

                        return true;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<EmptyEntity>() {
                    @Override
                    public void call(EmptyEntity superEntity) {
                        LogUtils.e("code--" + superEntity.code);
                        if ("200".equals(superEntity.code)) {


                            qiandao_user_main.setText("已签到");
                            qiandao_user_main.setTextColor(getResources().getColor(R.color.white));
                            initlevel();
                        } else {
                            TUtils.toast(superEntity.msg);
                        }

                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        LogUtils.e("throwable------" + throwable.getMessage());
                    }
                });
    }

    private void initlevel() {
        String uid = spu.getUser().getUid();
        Map<String, String> map = new HashMap<>();
        map.put("uid", uid);
        Factory.provideHttpService().MyLevel(ParamUtils.getRequestParam(map))
                .onBackpressureBuffer()
                .subscribeOn(Schedulers.io())
                .filter(new Func1<LevelEntity, Boolean>() {
                    @Override
                    public Boolean call(LevelEntity levelEntity) {
                        return true;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<LevelEntity>() {
                    @Override
                    public void call(LevelEntity levelEntity) {
                        LogUtils.e("code--" + levelEntity.code);
                        if ("200".equals(levelEntity.code)) {
                            spu.getUser().setUlevel("Lv" + levelEntity.data.getUserinfo().getLevel());
                        } else {
                            TUtils.toast(levelEntity.msg);
                        }
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        LogUtils.e("throwable------" + throwable.getMessage());
                    }
                });
    }
    private void isQianDao() {
        Map<String, String> map = new HashMap<>();
        if (spu.getUser() != null) {
            map.put("uid", spu.getUser().getUid());
        }
        Factory.provideHttpService().isSign(ParamUtils.getRequestParam(map))
                .onBackpressureBuffer()
                .subscribeOn(Schedulers.io())
                .filter(new Func1<IsSignEntity, Boolean>() {
                    @Override
                    public Boolean call(IsSignEntity superEntity) {

                        return true;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<IsSignEntity>() {
                    @Override
                    public void call(IsSignEntity superEntity) {
                        LogUtils.e("code--" + superEntity.code);
                        if ("200".equals(superEntity.code)) {
                            if ("1".equals(superEntity.data.getIssign())) {

                                qiandao_user_main.setText("已签到");
                                qiandao_user_main.setTextColor(getResources().getColor(R.color.white));
                            } else {
                                qiandao_user_main.setText("签到");
                                qiandao_user_main.setTextColor(getResources().getColor(R.color.white));
                            }
                        } else {
                            TUtils.toast(superEntity.msg);
                        }

                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        LogUtils.e("throwable------" + throwable.getMessage());
                    }
                });
    }

    private void thirdLogin(ThirdLoginBean tlb) {
        Map<String, String> map = new HashMap<>();
        map.put("userid", tlb.getUserid());
        map.put("gender", tlb.getGender());
        map.put("nickname", tlb.getNickname());
        map.put("photo", tlb.getPhoto());
        map.put("third", tlb.getThird());
        LogUtils.e("userid--" + tlb.getUserid());
        LogUtils.e("userid--" + tlb.getGender());
        LogUtils.e("userid--" + tlb.getNickname());
        LogUtils.e("userid--" + tlb.getPhoto());
        LogUtils.e("userid--" + tlb.getThird());
        Factory.provideHttpService().thirdLogin(ParamUtils.getRequestParam(map))
                .onBackpressureBuffer()
                .subscribeOn(Schedulers.io())
                .filter(new Func1<UserEntity, Boolean>() {
                    @Override
                    public Boolean call(UserEntity userEntity) {
                        LogUtils.e("code" + userEntity.code);
                        return "200".equals(userEntity.code);

                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<UserEntity>() {
                    @Override
                    public void call(UserEntity userEntity) {

                        LogUtils.e("login_success" + userEntity.data.getStatus());
//                        if ("1".equals(userEntity.data.getStatus())){
                        if ("200".equals(userEntity.code)) {
                            TUtils.toast("登录成功");
                            PageCtrl.start2BindMobileActivity(userEntity.data.getBindid(), activity);
                            spu.setUser(userEntity.data);

                            setLogin();
                        } else {
                            TUtils.toast(userEntity.msg);
                        }

                    }
                });

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        activity.unregisterReceiver(br);
    }
}
